package com.cl.cloud.tenant.logDemo;

import cn.hutool.core.util.RandomUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: liuzijian
 * @time: 2023-01-12 11:47
 */
public class AsyncLoggerImpl implements Logger {


    Map<String, AtomicOutPrint> atomicIntegerHashMap = new HashMap<>();

    public AsyncLoggerImpl() {
        this.atomicIntegerHashMap.put("A", new AtomicOutPrint("A"));
        this.atomicIntegerHashMap.put("B", new AtomicOutPrint("B"));
    }

    private String getRamdon() {
        return RandomUtil.randomBoolean() ? "A" : "B";
    }

    private void doLog(Integer threadNum, Integer logNum, String level) {
        int avgNum = logNum / threadNum;
        for (int i = 0; i < threadNum; i++) {
            if (i == threadNum - 1 && logNum > (avgNum * threadNum)) {
                avgNum += logNum - avgNum * threadNum;
            }
            int finalAvgNum = avgNum;
            new LogThread(() -> {
                for (int k = 0; k < finalAvgNum; k++) {
                    atomicIntegerHashMap.get(this.getRamdon()).print(level);
                }
            }, "pool-2-thread-" + (i + 1)).start();
        }
    }

    @Override
    public void info(Integer threadNum, Integer logNum) {
        this.doLog(threadNum, logNum, "INFO");
    }

    @Override
    public void error(Integer threadNum, Integer logNum) {
        this.doLog(threadNum, logNum, "ERROR");
    }

    @Override
    public void warn(Integer threadNum, Integer logNum) {
        this.doLog(threadNum, logNum, "WARN");
    }

    @Override
    public void debug(Integer threadNum, Integer logNum) {
        this.doLog(threadNum, logNum, "DEBUG");
    }
}
